'use strict';


import Base from './base.js';

const querystring = require('querystring');
var ttutil = require("../../business/ttutil");
var http = require('http');
var iconv = require('iconv-lite');
export default class extends Base {

    //请求ip信息  参数：请求信息，超时毫秒数，回调函数
requestWithTimeout=function(options,timeout,callback){
    var timeoutEventId,
        req=http.request(options,function(res){
             
            res.on('end',function(){
                clearTimeout(timeoutEventId);
                //console.log('response end...');
            });
             
            res.on('close',function(){
                clearTimeout(timeoutEventId);
                //console.log('response close...');
            });
             
            res.on('abort',function(){
                //console.log('abort...');
            });
             
            callback(res);
        });
         
    req.on('timeout',function(e){
        if(req.res){
            req.res('abort');
        }
        req.abort();
    });
 
timeoutEventId=setTimeout(function(){
        req.emit('timeout',{message:'have been timeout...'});
    },timeout);
     
    return req;
}

    indexAction() {

        var that=this;

        var getClientIP=function(req) {
            return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
                req.connection.remoteAddress || // 判断 connection 的远程 IP
                req.socket.remoteAddress || // 判断后端的 socket 的 IP
                req.connection.socket.remoteAddress;
        };
        var ip=getClientIP(that.http.req);
        
        var regIP = /(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/g;
        //console.log(ip);
        var ip= ip.match(regIP)[0];
        //var address ="未获取到IP信息";
        var address={"ip":ip,"address":"未获取到IP信息"};
        //console.log(ip);
        var option = { 
            hostname: "api.map.baidu.com",
            path: "/location/ip?ip="+ip+"&ak=57ff6fcd61f78fedc930a7eb43980a56"
            }; 
            var req = that.requestWithTimeout(option,4000, function(res2) {
                res2.on("data", function(chunk) {
                var htmldata=iconv.decode(chunk, "utf-8");
                htmldata=JSON.parse(htmldata);
                if(htmldata.status=="0")
                {
                    var addinfo=htmldata.content.address;
                    address={"ip":ip,"address":addinfo};
                }
                that.http.res.writeHead(200,{
                    "Content-Type":"text/plain;charset=utf-8"
                    });
                that.http.res.end( JSON.stringify( address));
            });
            }).on("error", function(e) {
               // console.log(e.message);
               that.http.res.end();
            }).on('timeout',function(e){
                that.http.res.writeHead(200,{
                    "Content-Type":"text/plain;charset=utf-8"
                    });
                    that.http.res.end(address);
            });
            req.end();
        
    }

    ///做备份使用
    index2Action() {
        var that=this;
        var getClientIP=function(req) {
            return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
                req.connection.remoteAddress || // 判断 connection 的远程 IP
                req.socket.remoteAddress || // 判断后端的 socket 的 IP
                req.connection.socket.remoteAddress;
        };
        
    
        var ip=getClientIP(that.http.req);
    
        var regIP = /(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/g;
        //console.log(ip);
        var ip= ip.match(regIP)[0];
    
        //var address ="未获取到IP信息";
        var address={"ip":ip,"address":"未获取到IP信息"};
        //console.log(ip[0]);
    
        var option = {
            hostname: "www.baidu.com",
            path: "/s?ie=utf-8&f=8&rsv_bp=1&wd="+ip
            };
            var req = that.requestWithTimeout(option,4000, function(res2) {
                res2.on("data", function(chunk) {
                var htmldata=iconv.decode(chunk, "utf-8");
                htmldata=htmldata.replace(/[\r\n\t]/g,"");
                htmldata=htmldata.replace(" ","");
                //console.log(htmldata);
    //<table><tr><td>
     //   		<span class="c-gap-right">IP地址:&nbsp;59.61.184.143</span>福建省福州市 电信	    
      //  </td></tr></table>  
                //console.log(iconv.decode(chunk, "utf-8"));
                var patt = /.*?<table[^>]*?>\s*<tr[^>]*?>\s*<td[^>]*?>\s*<span[^>]*?>(.*?)\s*<\/span>(.*?)<\/td>.*?/;
                　//　var res = reg.test(htmldata);
                //console.log(res);
                var result = patt.test(htmldata);
                
                if(result)
                {
                    var addinfo = patt.exec(htmldata)[2].trim();
                    //console.log(addinfo);
                    that.http.res.writeHead(200,{
                        "Content-Type":"application/json;charset=utf-8"
                        });
                    address={"ip":ip,"address":addinfo};
                    that.http.res.end( JSON.stringify( address));
                }
            });
            }).on("error", function(e) {
               // console.log(e.message);
               that.http.res.end();
            }).on('timeout',function(e){
                that.http.res.writeHead(200,{
                    "Content-Type":"text/plain;charset=utf-8"
                    });
                    that.http.res.end(address);
            });
            req.end();
        
    }
}